package com.symbio.ishenapi.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.common.kit.ISConst;
import io.jboot.Jboot;
import io.jboot.component.redis.JbootRedis;

/**
 * 全局拦截器
 */
public class GlobalInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();

        // TODO 跨域处理，若JS本地调试需要将注释放开，但提交到代码仓库时需要注释
        controller.getResponse().setHeader("Access-Control-Allow-Origin", "*");
        controller.getResponse().setHeader("Access-Control-Allow-Credentials",
                "true");
        controller.getResponse().setHeader("Access-Control-Allow-Methods", "*");
        controller.getResponse().setHeader("Access-Control-Allow-Headers", "*");
        controller.getResponse().setHeader("Access-Control-Expose-Headers", "*");
        if (controller.getRequest().getMethod().equals("OPTIONS")) {
            controller.renderJson("");
            return;
        }

        String token = controller.getHeader("X-Token");
        controller.setAttr("X-Token", token);

        if (StrKit.isBlank(token)) {
            // TODO 根据实际情况放开不需要Token认证的请求: if (!inv.getActionKey().equals("/login")) { ... }
            if (inv.getActionKey().equals("/login")){
                inv.invoke();
            }else if(inv.getActionKey().equals("/TmUserManage/userLogin")){
                inv.invoke();
            }else if(inv.getActionKey().equals("/sms/sendMessage")){
                inv.invoke();
            }else if(inv.getActionKey().equals("/sms/judge")){
                inv.invoke();
            }else {
                controller.renderJsonError(40000);
                return;
            }
        } else {
            JbootRedis redis = Jboot.me().getRedis();

            Object info = redis.get(token);
            System.out.println("1111111111======" + info.toString());
            if (info == null) {
                controller.renderJsonError(40000);
                return;
            }

            controller.setAttr(ISConst.GLOBAL_USER, info);
        }
        inv.invoke();
    }
}
